// pages/address/list/index.js
const appUser = getApp();
const db = wx.cloud.database();
const _ = db.command;
Page({
  // 页面的初始数据
  data: {
    isSelect: false,
    addressList: []
  },
  
  toAdd() {
    console.log("..")
    wx.navigateTo({
      url: "/modules/settingModule/pages/address/add/index"
    })
  },
  onLoad(options) {
    db.collection("user2").where({
      _openid: appUser.globalData.userOpenid
    }).get({
      success: res => {
        console.log(res)
        this.setData({
          addressList: res.data[0].address
        })
      }
    })
    if (options.select) {
      this.setData({
        isSelect: true
      })
    }
  },
  //删除地址
  delete(e) {
    console.log(e.currentTarget.dataset.address)
    db.collection("user2").where({
      _openid: appUser.globalData.userOpenid
    }).update({
      data: {
        address: _.pull(e.currentTarget.dataset.address)
      }
    })
    this.data.addressList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      addressList:this.data.addressList
    })
  },
  toSelect(e) {
    console.log()
    var index = e.currentTarget.dataset.index
    var a = this.data.addressList[index]
    if (this.data.isSelect) {
      var pages = getCurrentPages(); //当前页面
      var prevPage = pages[pages.length - 2]; //上个页面
      // 直接给上一个页面赋值
      prevPage.setData({
        address: a.name + " " + a.address + " " + a.phton
      });
      wx.navigateBack({
        delta: 1
      })
    }

  },
  // 去编辑页面
  toEdit(e) {
    console.log(e)
    wx.navigateTo({
      url: '../add/index?id=' + e.currentTarget.dataset.id
    })
  }
})